package org.csu.web.servlets;

import org.csu.domain.Account;
import org.csu.domain.Product;
import org.csu.service.CategortService;
import org.csu.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

public class SearchProductsServlet extends HttpServlet {
    String keyword;
    private static final String SEARCH_PRODUCTS="/WEB-INF/jsp/catalog/SearchProducts.jsp";
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        keyword=req.getParameter("keyword");
        CategortService service = new CategortService();
        Product pruduct = service.getProductByname(keyword);
        List<Product> productList= service.searchProductList(keyword);
        HttpSession session = req.getSession();
        productList.add(pruduct);
        session.setAttribute("pruduct",pruduct);
        session.setAttribute("productList",productList);
        Account account = (Account)session.getAttribute("account");

        if(account != null){
            HttpServletRequest httpRequest= req;
            String strBackUrl = "http://" + req.getServerName() + ":" + req.getServerPort()
                    + httpRequest.getContextPath() + httpRequest.getServletPath() + "?" + (httpRequest.getQueryString());

            LogService logService = new LogService();
            String logInfo = logService.logInfo(" ") + strBackUrl + " 查找商品" + "  " + productList;
            logService.insertLogInfo(account.getUsername(), logInfo);
        }
        req.getRequestDispatcher(SEARCH_PRODUCTS).forward(req,resp);
    }
}
